<?php
/*由bean脚本生成 powerBy--joe*/
namespace app\common\manage;
use app\common\bean\CategoryBean;
use app\common\bean\CategoryGroupBean;
use app\common\bean\ConfigBean;
use app\common\bean\ContentBean;
use app\common\bean\DistributionBean;
use app\common\bean\GlobalBean;
use app\common\bean\StoreUserBean;
use app\common\bean\SwiperBean;
use app\common\bean\UserBean;
use app\common\enum\ConfigSpecialEnum;
use app\common\enum\StoreStatusEnum;
use app\common\enum\StoreUserIsUpdatePwEnum;
use app\common\model\CategoryGroupModel;
use app\common\model\CategoryModel;
use app\common\model\ConfigModel;
use app\common\model\ContentModel;
use app\common\model\DistributionModel;
use app\common\model\StoreUserModel;
use app\common\model\SwiperModel;
use app\common\utils\QQEmailUtil;
use app\common\validate\StoreValidate;
use app\common\model\StoreModel;
use app\common\bean\StoreBean;
use app\common\bean\ListMap;
use app\common\utils\TimeUtil;
use app\common\exception\MyException;
use Exception;
use think\Model;

class StoreManage extends BaseManage
{
	/**
	* @return StoreManage
	*/
	static function getInstance(){
		return parent::getInstance();
	}

    public function getPaginaList(ListMap $listMap){//根据距离获取商家列表
        $contact_addr_lat = $listMap->getParameter('contact_addr_lat');
        $contact_addr_lng = $listMap->getParameter('contact_addr_lng');
        $disField = getDisField($contact_addr_lat, $contact_addr_lng, StoreBean::$contactAddrLat, StoreBean::$contactAddrLng);
        $conditionMap = new ListMap();
        $conditionMap->setField([StoreBean::$companyName,StoreBean::$contactAddr, StoreBean::$id, $disField]);
        $conditionMap->setOrder("distance ASC");
        $conditionMap->setParameter(StoreBean::$status, StoreStatusEnum::SUCCESS);
        $storeList = StoreModel::getInstance()->getList($conditionMap);
        foreach ($storeList->getList() as $s){
            $s['distance'] = $s['distance']>1000 ? number_format($s['distance']/1000, 1).'公里' : $s['distance'].'米';
            $newList[] = $s;
        }
        $storeList->setList($newList);
        return $storeList;
    }
	/**
	 * @desc 获取分页数据
	 * @param ListMap $listMap
	 * @return ListMap $listMap
	 * @throws Exception
	**/
	public function getPaginatorList(ListMap $listMap) {
		$conditionMap = new ListMap();
		if($timeArray = TimeUtil::getInstance()->dealBetweenTime($listMap))
		$conditionMap->setParameter(StoreBean::$alias.POINST.StoreBean::$createdAt,$timeArray);
		$conditionMap->setAlias(StoreBean::$alias);
		$listMap->setField(StoreBean::$alias.ALL_FIELD);
		!$this->getParamBool($listMap,"orderFieldName") ?: $conditionMap->setOrder($listMap->getParameter('orderFieldName').SPACE.$listMap->getParameter('orderType'));
		$conditionMap->setParameter(StoreBean::$companyName,["like","%{$listMap->getParameter(StoreBean::$companyName)}%"]);
		$conditionMap->setParameter(StoreBean::$status,$conditionMap->getParameter(StoreBean::$status));
        $conditionMap->setWith('user');
		$resultMap = StoreModel::getInstance()->getList($conditionMap);
		$resultMap?:MyException::throwMyException("查询数据失败");
		return $resultMap;
	}
	
	/**
	 * @desc 添加数据
	 * @param StoreBean $storeBean
	 * @return int int
	 * @throws Exception
	**/
	public function add($storeBean) {
		StoreValidate::getInstance()->goCheck(StoreValidate::$add,$storeBean->getData());
		// Todo:添加业务处理代码...


		$storeBean->setCreatedAt(TimeUtil::getInstance()->getTimeNow());
		$result = StoreModel::getInstance()->addDataGetInsertId($storeBean->getData());
		$result ?: MyException::throwMyException("插入数据失败");
		return $result;
	}
	
	/**
	 * @desc 编辑数据
	 * @param StoreBean $storeBean
	 * @return int int
	 * @throws Exception
	**/
	public function edit($storeBean) {
		StoreValidate::getInstance()->goCheck(StoreValidate::$edit,$storeBean->getData());
		if($storeBean->getParameter('password')){
		    $data[StoreUserBean::$password] = md5($storeBean->getParameter('password'));
		    StoreUserModel::getInstance()->where([StoreUserBean::$storeId=>$storeBean->getId()])->update($data);
        }
        $storeBean->removeField('password');
        $storeBean->setUpdatedAt(date('Y-m-d H:i:s'));
		$result = StoreModel::getInstance()->updatedData([StoreBean::$id => $storeBean->getId()],$storeBean->getData());
		$result ?: MyException::throwMyException("更新失败");
		return $result;
	}
	
	/**
	 * @desc 删除数据
	 * @param StoreBean $storeBean
	 * @return int int
	 * @throws Exception
	**/
	public function delete($storeBean) {
		StoreValidate::getInstance()->goCheck(StoreValidate::$pkId,$storeBean->getData());
		// Todo:添加业务处理代码...


		$result = StoreModel::getInstance()->deleteData([StoreBean::$id => $storeBean->getId()]);
		$result ?: MyException::throwMyException("删除失败");
		return $result;
	}
	
	/**
	 * @desc 根据主建获取数据
	 * @param StoreBean $storeBean
	 * @return StoreBean $storeBean
	 * @throws Exception
	**/
	public function getInfo($storeBean) {
		StoreValidate::getInstance()->goCheck(StoreValidate::$pkId,$storeBean->getData());
		$result = StoreModel::getInstance()->selectData([StoreBean::$id => $storeBean->getId()]);
		$result ?: MyException::throwMyException("获取信息失败");
		$storeBean->setData($result);
		return $storeBean;
	}

    /**
     * @desc 根据主建获取数据
     * @param StoreBean $storeBean
     * @return array|bool|false
     * @throws Exception
     **/
    public function getStoreApply(UserBean $userBean) {
        $result = StoreModel::getInstance()->selectData([StoreBean::$userId => $userBean->getId()]);
        return $result;
    }

    /** 签约成功、失败
     * @param StoreBean $storeBean
     * @return bool
     * @throws Exception
     */
    public function reviewStore(StoreBean $storeBean){
        $resouceStoreBean = new StoreBean();
        $resouceStoreBean->setId($storeBean->getId());
        $resouceStoreBean = $this->getInfo($resouceStoreBean);
        //$resouceStoreBean->getStatus() === StoreStatusEnum::WAITREVIEW ?: MyException::throwMyException("申请待审核状态");
        StoreModel::getInstance()->updatedData(array(StoreBean::$id => $storeBean->getId()),$storeBean->getData());
        $store = StoreUserModel::getInstance()->getByPhone($resouceStoreBean->getContactPhone());

        if($storeBean->getStatus() == StoreStatusEnum::SUCCESS && !$store){//生成商家账户 、 发送邮件通知
            $storeUserBean = new StoreUserBean();
            $storeUserBean->setUsername($resouceStoreBean->getContactPhone());
            $storeUserBean->setStoreId($resouceStoreBean->getId());
            $storeUserBean->setName($resouceStoreBean->getCompanyName());
            $storeUserBean->setStoreRoleId(GlobalBean::$superStoreRoleId);
            $storeUserBean->setUsername($resouceStoreBean->getEmail());
            $storeUserBean->setPhone($resouceStoreBean->getContactPhone());
            $storeUserBean->setIsUpdatePw(StoreUserIsUpdatePwEnum::NEED);
            $storeUserBean->setPassword(123456);
            StoreUserManage::getInstance()->add($storeUserBean);
            //$emailResult = QQEmailUtil::getInstance()->sendEmail($resouceStoreBean->getEmail(),"商家账户分配","登录用户:商家邮箱  登录密码:{$randCode}+手机号");
            //$emailResult ?: MyException::throwMyException("发送通知邮件失败");
            return true;
        }
        return false;
    }

    /**生成商家默认数据
     * @param $storeId
     * @throws Exception
     */
    public function generateStoreData($storeId){
        intval($storeId) ?: MyException::throwMyException("商家id不可为空");
        $swiperList = SwiperModel::getInstance()->selectData([SwiperBean::$storeId => 0],true);
        $contentList = ContentModel::getInstance()->selectData([ContentBean::$storeId => 0],true);
        $categoryList = CategoryModel::getInstance()->selectData([CategoryBean::$storeId => 0],true);
        $distribution = DistributionModel::getInstance()->selectData([DistributionBean::$storeId=>0], true);

        ConfigModel::getInstance()->startTrans();
        foreach ($swiperList as &$s){
            unset($s['domain_url']);
        }
        foreach ($contentList as &$c){
            unset($c['domain_pic']);
            unset($c['domain_icon']);
        }
        $swiperDatas = $this->dealStoreDefaultData($swiperList,new SwiperBean(),$storeId);
        $contentDatas = $this->dealStoreDefaultData($contentList,new ConfigBean(),$storeId);
        $categoryDatas = $this->dealStoreDefaultData($categoryList,new CategoryBean(),$storeId);
        $distributionGroupDatas = $this->dealStoreDefaultData($distribution, new DistributionBean(), $storeId);

        SwiperModel::getInstance()->allowField(true)->insertAll($swiperDatas);
        ContentModel::getInstance()->allowField(true)->insertAll($contentDatas);
        CategoryModel::getInstance()->allowField(true)->insertAll($categoryDatas);
        DistributionModel::getInstance()->allowField(true)->insertAll($distributionGroupDatas);

        $categoryDatas = CategoryModel::getInstance()->selectData([CategoryBean::$storeId=>$storeId], true);
        $insert_data = CategoryGroupManage::getInstance()->cateCartesian($categoryDatas);
        CategoryGroupModel::getInstance()->allowField(true)->insertAll($insert_data);

        ConfigModel::getInstance()->commit();
    }
    /**
     * @param $list
     * @param ConfigBean|SwiperBean|ContentBean|CategoryBean|CategoryGroupBean $bean
     * @param $storeId
     * @return array
     */
    private function dealStoreDefaultData($list, $bean,$storeId){
        $datas = [];
        foreach ($list as $value){
            /**@var $value Model*/
            $bean->setData($value instanceof Model ? $value->toArray() : $value);
            $bean->setStoreId($storeId);
            $data = $bean->getData();unset($data["id"]);unset($data["category_name_string"]);
            array_push($datas,$data);
        }
        return $datas;
    }
}
